﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Autofac;
using ComputerVision.ANN;
using ComputerVision.BaseForm;
using ComputerVision.Common;
using ComputerVision.Data;
using ComputerVision.Services;
using Emgu.CV;
using Emgu.CV.Structure;
using System;
using System.Drawing;
using RawInput_dll;

namespace ComputerVision
{
    public partial class frmXeRaNew : frmObject
    {
        private IService<ConfigrationCamera> _configCamera;
        private IService<LoaiXe> _loaiXe;
        private IService<VeXe> _veXe;
        private IService<Xe> _xe;
        private VeXe _veXe2;
        private Xe _xe2;
        private Xe _xe3;
        private readonly Common.ImageProcess _process;
        //private Capture cap2;
        //private Capture cap3;
        //private int _cmr2;
        //private int _cmr3;
        //private Image<Bgr, byte> img2; //nhận diện mặt người ra                
        private Bitmap img2end = null; //nhận diện mặt người ra                
        //private Image<Bgr, byte> img3; //nhận diện mặt người ra                
        private Bitmap img3end = null; //nhận diện mặt người ra                
        //private Image<Gray, byte> imgGray2;
        private Image<Bgr, Byte> biensoxera;
        private string _computerName;
        string bienso;
        private System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("\\d\\d-[A-Z][0-9A-Z]-\\d{4,5}");
        private System.Text.RegularExpressions.Regex regexoto = new System.Text.RegularExpressions.Regex("\\d\\d-[A-Z]-\\d{4,5}");
        //private string _soVe;

        private Bitmap imgT = null;
        private Bitmap imgS = null;

        private readonly RawInput _rawinput;
        private string cardNumber = string.Empty;
        private bool isCardReader = false;
        private bool readOk = false;
        private string tempNumber = string.Empty;
        private string readerDevide = string.Empty;

        private string tempFile = string.Empty;
        private ImgageArrayRa imageArray;
        private FileUtil fileUtil;
        private int countT = 0;
        private int countS = 0;
        private string cardStatus = string.Empty;

        public frmXeRaNew()
        {
            InitializeComponent();

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            _rawinput = new RawInput(Handle);
            _rawinput.CaptureOnlyIfTopMostWindow = true;    // Otherwise default behavior is to capture always
            _rawinput.AddMessageFilter();                   // Adding a message filter will cause keypresses to be handled
            _rawinput.KeyPressed += OnKeyPressed;

            _computerName = Environment.MachineName;
            _configCamera = Program.Container.Resolve<IService<ConfigrationCamera>>();
            _loaiXe = Program.Container.Resolve<IService<LoaiXe>>();
            _xe = Program.Container.Resolve<IService<Xe>>();
            _veXe = Program.Container.Resolve<IService<VeXe>>();
            _process = new ImageProcess();
            //_soVe = txtSoVe.Text;
            LoadLoaiXe();
            fileUtil = new FileUtil();

            axLiveSau.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveTruoc_OnGetPicture);
            axLiveTruoc.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveSau_OnGetPicture);
        }

        void axLiveSau_OnGetPicture(object sender, AxLIVEXLib._DLiveXEvents_OnGetPictureEvent e)
        {
            if (countS == 1)
            {
                return;
            }
            axLiveTruoc.StartGrapImage(false);
            imgS = ImageProcess.ImageConvert.GetImageFromIPicture(e.mPict);

            img3end = imgS;
            imgRaSau.Image = imgS;
            countS = 1;
        }

        void axLiveTruoc_OnGetPicture(object sender, AxLIVEXLib._DLiveXEvents_OnGetPictureEvent e)
        {
            if (countT == 1)
            {
                return;
            }
            axLiveSau.StartGrapImage(false);
            imgT = ImageProcess.ImageConvert.GetImageFromIPicture(e.mPict);

            img2end = imgT;
            imgRaTruoc.Image = imgT;
            countT = 1;
        }

        //private void CaptureWC()
        //{
        //    //_cmr2 = 0;
        //    cap2 = new Capture(_cmr3);
        //    cap2.ImageGrabbed += wc2;
        //    cap2.Start();

        //    //_cmr3 = 0;
        //    cap3 = new Capture(_cmr2);
        //    cap3.ImageGrabbed += wc1detectFace;
        //    cap3.Start();
        //}

        //private void wc1detectFace(object sender, EventArgs e)
        //{
        //    var faceDetector1 = new CascadeClassifier("haarcascade_frontalface_default.xml");
        //    img2 = cap3.RetrieveBgrFrame();
        //    imgGray2 = img2.Convert<Gray, byte>();
        //    foreach (var face in faceDetector1.DetectMultiScale(imgGray2, 1.1, 10, new Size(20, 20), Size.Empty))
        //    {
        //        img2.Draw(face, new Bgr(Color.White), 1);
        //    }
        //    //imgRaTruoc.Image = img2;
        //    //picRaTruoc.Image = img2.Bitmap;
        //}

        //private void wc2(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        img3 = cap2.RetrieveBgrFrame();
        //        //imgRaSau.Image = img3;
        //        //picRaSau.Image = img3.Bitmap;
        //    }
        //    catch (Exception ex)
        //    {

        //    }
        //}

        private void button1_Click(object sender, EventArgs e)
        {
            if (Timer_Ra.Enabled == false)
            {
                axLiveTruoc.StartGrapImage(true);
                axLiveSau.StartGrapImage(true);
                Timer_Ra.Enabled = true;
                picBiensora.Image = null;
                btnDocLai.Text = @"Ngừng";
                lblTrangThai.Text = Constants.StatusReading.Reading;
                lblTrangThai.ForeColor = Color.Blue;
            }
            else
            {
                axLiveTruoc.StartGrapImage(false);
                axLiveSau.StartGrapImage(false);
                Timer_Ra.Enabled = false;
                picBiensora.Image = null;
                btnDocLai.Text = @"Đọc tiếp";
                lblTrangThai.Text = Constants.StatusReading.Stopped;
                lblTrangThai.ForeColor = Color.Red;
            }
            txtSoVe.Focus();
        }

        private void frmXeRa_Load(object sender, System.EventArgs e)
        {
            //CaptureWC();
            foreach (LoaiXe loaiXe in cbLoaixe.Items)
            {
                if (loaiXe.Ten.ToUpper().Equals(Constants.Xe.XeMay.ToUpper()))
                {
                    cbLoaixe.SelectedItem = loaiXe;
                    break;
                }
            }

            Save();

            var item = _configCamera.ToList().ToList().FirstOrDefault(p => p.ComputerName.Contains(_computerName));
            if (item != null)
            {
                readerDevide = item.CardReader;

                this.axLiveSau.IpAddress = item.Server;
                this.axLiveSau.CommandPort = System.Convert.ToInt32("4550");
                this.axLiveSau.DataPort = System.Convert.ToInt32("5550");
                this.axLiveSau.AudioDataPort = System.Convert.ToInt32("6550");
                this.axLiveSau.DisablePWD = true;
                this.axLiveSau.DefaultCam = short.Parse(item.Cam3.ToString());
                this.axLiveSau.UserName = item.UserID;
                this.axLiveSau.Password = item.Password;
                this.axLiveSau.PlayX();

                this.axLiveTruoc.IpAddress = item.Server;
                this.axLiveTruoc.CommandPort = System.Convert.ToInt32("4550");
                this.axLiveTruoc.DataPort = System.Convert.ToInt32("5550");
                this.axLiveTruoc.AudioDataPort = System.Convert.ToInt32("6550");
                this.axLiveTruoc.DisablePWD = true;
                this.axLiveTruoc.DefaultCam = short.Parse(item.Cam4.ToString()); ;
                this.axLiveTruoc.UserName = item.UserID;
                this.axLiveTruoc.Password = item.Password;
                this.axLiveTruoc.PlayX();
            }
            else
            {
                AlertList.Warning("Bạn phải thiết lập camera và thiết bị đọc thẻ cho hệ thống trước khi sử dụng.");
            }
        }

        private void Timer_Ra_Tick(object sender, EventArgs e)
        {
            try
            {
                biensoxera = new Image<Bgr, Byte>((Bitmap)imgRaSau.Image);

            }
            catch (Exception)
            {
            }

            try
            {
                bienso = _process.docbienso(biensoxera, picBiensora, neuralNetwork);

            }
            catch (Exception)
            {

            }

            //try
            //{
            //    img3end = imgS;
            //    img2end = imgT;
            //}
            //catch (Exception)
            //{
            //}

            try
            {
                if (regex.IsMatch(bienso))
                {
                    Timer_Ra.Enabled = false;
                    //  picTruoc.Image = imgVaoTruoc.Image.Bitmap;
                    //  picTruoc.Visible = true;
                    //  picSau.Image = imgVaoSau.Image.Bitmap;
                    //  picSau.Visible = true;

                    txtBiensora.Text = bienso;
                    foreach (LoaiXe loaiXe in cbLoaixe.Items)
                    {
                        if (loaiXe.Ten.ToUpper().Equals(Constants.Xe.XeMay.ToUpper()))
                        {
                            cbLoaixe.SelectedItem = loaiXe;
                            break;
                        }
                    }
                    //  btnDoclai.Text = "Đọc tiếp";
                    //  MarqueeProgressBarControl1.Enabled = false;
                    //  cbLoaixevao.SelectedItem = "Xe máy";
                    //  txtNgayvao.Text = DateAndTime.Now.ToString("dd/MM/yyyy");
                    // txtGiovao.Time = DateAndTime.Now;
                    lblTrangThai.Text = Constants.StatusReading.Stopped;
                    lblTrangThai.ForeColor = Color.Red;
                    btnDocLai.Text = @"Đọc tiếp";
                }
                else if (regexoto.IsMatch(bienso))
                {
                    Timer_Ra.Enabled = false;
                    txtBiensora.Text = bienso;

                    foreach (LoaiXe loaiXe in cbLoaixe.Items)
                    {
                        if (loaiXe.Ten.ToUpper().Equals(Constants.Xe.Oto.ToUpper()))
                        {
                            cbLoaixe.SelectedItem = loaiXe;
                            break;
                        }
                    }

                    lblTrangThai.Text = Constants.StatusReading.Stopped;
                    lblTrangThai.ForeColor = Color.Red;
                    btnDocLai.Text = @"Đọc tiếp";
                }
                //else
                //{
                //    axLiveSau.StartGrapImage(true);
                //}
            }
            catch (Exception)
            {

            }

        }

        private void LoadLoaiXe()
        {
            var loaixe = _loaiXe.ToList().ToList();
            foreach (LoaiXe loai in loaixe)
            {
                cbLoaixe.Items.Add(loai);
            }
        }

        #region Validation

        private bool ValidCard()
        {
            _veXe = Program.Container.Resolve<IService<VeXe>>();
            _xe = Program.Container.Resolve<IService<Xe>>();

            _veXe2 = _veXe.Detail(txtSoVe.Text.Trim());
            if (txtSoVe.Text.Trim().Equals(string.Empty))
            {
                lblTrangThaiThe.Text = @"Đang chờ";
                lblTrangThaiThe.ForeColor = Color.Black;
                return false;
            }

            if (_veXe2 == null)
            {
                lblTrangThaiThe.Text = Constants.VeMessages.VeKhongCoTrongDuLieu;
                cardStatus = Constants.VeMessages.VeKhongCoTrongDuLieu;
                lblTrangThaiThe.ForeColor = Color.Red;
                AlertList.Error(cardStatus);
                return false;
            }

            if (_veXe2.Status.Equals(Constants.StatusVeXe.MatVe))
            {
                lblTrangThaiThe.Text = Constants.VeMessages.MatVe;
                cardStatus = Constants.VeMessages.MatVe;
                lblTrangThaiThe.ForeColor = Color.Red;
                AlertList.Error(cardStatus);
                return false;
            }

            if (_veXe2.Status.Equals(Constants.StatusVeXe.InActive))
            {
                lblTrangThaiThe.Text = Constants.VeMessages.VeKhongHoatDong;
                cardStatus = Constants.VeMessages.VeKhongHoatDong;
                lblTrangThaiThe.ForeColor = Color.Red;
                AlertList.Error(cardStatus);
                return false;
            }

            _xe2 = _xe.ToList().ToList()
                            .OrderByDescending(b => b.NgayVao)
                            .FirstOrDefault(p => p.SoVe.Equals(txtSoVe.Text.Trim()));
            if (_xe2 != null && _xe2.NgayRa != null && _xe2.ImgRaTruoc != null && _xe2.ImgRaSau != null)
            {
                lblTrangThaiThe.Text = Constants.VeMessages.VeChuaVao;
                cardStatus = Constants.VeMessages.VeChuaVao;
                lblTrangThaiThe.ForeColor = Color.Red;
                AlertList.Error(cardStatus);
                return false;
            }

            lblTrangThaiThe.Text = Constants.VeMessages.VeHopLe;
            lblTrangThaiThe.ForeColor = Color.Blue;

            //else
            //{
            //    lblTrangThaiThe.Text = @"";
            //}

            return true;
        }

        protected bool Validator()
        {
            if (string.IsNullOrEmpty(txtSoVe.Text))
            {
                AlertList.Error("Bạn chưa nhập số vé. Xin vui lòng kiểm tra lại.");
                txtSoVe.Focus();
                return false;
            }

            int result;
            if (!int.TryParse(txtSoVe.Text, out result))
            {
                AlertList.Error("Bạn nhập số vé không hợp lệ. Xin vui lòng kiểm tra lại");
                txtSoVe.Focus();
                return false;
            }

            var soVe = _veXe.Detail(txtSoVe.Text.Trim());
            if (soVe == null)
            {
                AlertList.Error("Bạn nhập số vé không có trong dữ liệu. Xin vui lòng kiểm tra lại");
                txtSoVe.Focus();
                return false;
            }

            if (!soVe.Status.Equals(Constants.StatusVeXe.Active))
            {
                AlertList.Error("Hiện tại số vé này không hoạt động. Xin vui lòng kiểm tra lại");
                txtSoVe.Focus();
                return false;
            }

            if (cbLoaixe.SelectedItem == null)
            {
                AlertList.Error("Bạn chưa chọn loại xe. Xin vui lòng kiểm tra lại.");
                cbLoaixe.Focus();
                return false;
            }

            //var loaiXe = cbLoaixe.SelectedItem as LoaiXe;

            //if (!loaiXe.Ten.ToUpper().Equals(Constants.Xe.XeDap.ToUpper()) && string.IsNullOrEmpty(txtBiensora.Text))
            //{
            //    AlertList.Error("Bạn chưa nhập biển số xe ra. Xin vui lòng kiểm tra lại.");
            //    txtBiensora.Focus();
            //    return false;
            //}

            //if (!txtBienSoVao.Text.Replace("-", "").Replace(".", "").ToUpper().Equals(txtBiensora.Text.Replace("-", "").Replace(".", "").ToUpper()))
            //{
            //    AlertList.Error("Biển số ra và vào không giống nhau. Xin vui lòng kiểm tra lại.");
            //    txtBiensora.Focus();
            //    return false;
            //}

            return true;
        }

        #endregion

        private void btnTiep_Click(object sender, EventArgs e)
        {
            if (Validator())
            {
                this.imageArray = new ImgageArrayRa(img2end, img3end, picBiensora.Image, tempFile, fileUtil.tempFolderToday);

                if (fileUtil.WriteImagesRa(this.imageArray))
                {
                    Edit(txtSoVe.Text.Trim());
                    txtSoVe.Focus();
                }
                else
                {
                    AlertList.Error("Không ghi được ảnh chụp từ camera. Vui lòng kiểm tra lại hệ thống.");
                }
            }
        }

        private void timerClock_Tick(object sender, EventArgs e)
        {
            dtpGioRa.Value = DateTime.Now;
            dtpNgayRa.Value = DateTime.Now;
            //valid card
            //if (!txtSoVe.Text.Trim().Equals(string.Empty) && !txtSoVe.Text.Trim().Equals(_soVe))
            //{
            //    ValidCard();
            //    _soVe = txtSoVe.Text.Trim();
            //}
        }

        #region Edit

        protected void Edit(string soVe)
        {
            //var item = _xe.ToList().ToList()
            //    .Where(p => p.SoVe.Equals(soVe))
            //    .OrderByDescending(b => b.NgayVao)
            //    .ThenByDescending(c => c.GioVao)
            //    .FirstOrDefault(a => a.BienSoXe.Equals(bienSoXe));

            var item = _xe.ToList().ToList()
                    .OrderByDescending(b => b.NgayVao)
                    .FirstOrDefault(p => p.SoVe.Equals(soVe));
            if (item != null)
            {
                item.NgayRa = DateTime.Now;
                item.ImgRaTruoc = this.imageArray.NameTruocUrl;
                item.ImgRaSau = this.imageArray.NameTruocUrl;
                item.ImgBienXeRa = this.imageArray.NameBienSoUrl;

                item.Modified = DateTime.Now;
                item.ModifiedBy = Constants.CurrentUser;
                _xe.Update(item);

                //Reset controls
                cardStatus = string.Empty;
                txtSoVe.Text = string.Empty;
                txtBienSoVao.Text = string.Empty;
                dtpGioVao.Text = string.Empty;
                dtpNgayRa.Text = string.Empty;
                txtBiensora.Text = string.Empty;
                picBienSoVao.Image = null;
                picBiensora.Image = null;
                txtSoVe.Focus();
            }
        }

        #endregion

        private void txtSoVe_MouseEnter(object sender, EventArgs e)
        {
            txtSoVe.SelectAll();
        }

        private void txtSoVe_MouseDown(object sender, MouseEventArgs e)
        {
            txtSoVe.SelectAll();

        }

        //Neural Network Object With Output Type String
        private NeuralNetwork<string> neuralNetwork = null;

        //Data Members Required For Neural Network
        private Dictionary<string, double[]> TrainingSet;
        private int av_ImageHeight = 0;
        private int av_ImageWidth = 0;
        private int NumOfPatterns = 0;

        private void Save()
        {

            string[] Images = Directory.GetFiles(Application.StartupPath + @"\ImageTrainning", "*.bmp");
            NumOfPatterns = Images.Length;
            av_ImageHeight = 0;
            av_ImageWidth = 0;
            foreach (string s in Images)
            {
                var Temp = new Bitmap(s);
                av_ImageHeight += Temp.Height;
                av_ImageWidth += Temp.Width;
                Temp.Dispose();
            }
            av_ImageHeight /= NumOfPatterns;
            av_ImageWidth /= NumOfPatterns;

            int networkInput = av_ImageHeight * av_ImageWidth;
            GenerateTrainingSet();
            CreateNeuralNetwork();
        }

        private void CreateNeuralNetwork()
        {
            if (TrainingSet == null)
                throw new Exception("Unable to Create Neural Network As There is No Data to Train..");

            neuralNetwork = new NeuralNetwork<string>
                (new BP3Layer<string>(av_ImageHeight * av_ImageWidth, 295, 98, NumOfPatterns), TrainingSet);

            neuralNetwork.MaximumError = 1.1;
            neuralNetwork.LoadNetwork(Application.StartupPath + @"\ImageTrainning\Model.net");
        }

        private void GenerateTrainingSet()
        {
            // string[] Patterns = Directory.GetFiles(@"C:\Users\bienphongvnn\Desktop\hinhanhhuanluyen", "*.bmp");
            string[] Patterns = Directory.GetFiles(Application.StartupPath + @"\ImageTrainning", "*.bmp");
            TrainingSet = new Dictionary<string, double[]>(Patterns.Length);
            foreach (string s in Patterns)
            {
                var Temp = new Bitmap(s);
                TrainingSet.Add(Path.GetFileNameWithoutExtension(s),
                    ImageProcessing.ToMatrix(Temp, av_ImageHeight, av_ImageWidth));
                Temp.Dispose();
            }


        }

        private void frmXeRa_KeyDown(object sender, KeyEventArgs e)
        {
            if (!isCardReader)
            {
                if (e.KeyCode == Keys.F2)
                {
                    btnDocLai.PerformClick();
                }
                else if (e.KeyCode == Keys.Enter)
                {
                    if (!txtSoVe.Focused && cardStatus.Equals(string.Empty))
                    {
                        btnTiep.PerformClick();
                        //btnDocLai.PerformClick();
                    }
                    else if (!txtSoVe.Focused && !cardStatus.Equals(string.Empty))
                    {
                        AlertList.Error(cardStatus);
                    }
                }
                else if (e.KeyCode == Keys.F1)
                {
                    cardNumber = string.Empty;
                    txtSoVe.Text = string.Empty;
                    txtSoVe.Focus();
                    cbLoaixe.SelectedItem = cbLoaixe.Items[1];

                }
                else if (e.KeyCode == Keys.F3)
                {
                    cbLoaixe.SelectedItem = cbLoaixe.Items[1];
                    cbLoaixe.SelectedItem = cbLoaixe.Items[0];
                    //txtSoVe.Text = string.Empty;
                    txtBiensora.Focus();
                }
            }
        }

        private static void CurrentDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
        {
            var ex = e.ExceptionObject as Exception;

            if (null == ex) return;

            // Log this error. Logging the exception doesn't correct the problem but at least now
            // you may have more insight as to why the exception is being thrown.
            //Debug.WriteLine("Unhandled Exception: " + ex.Message);
            //Debug.WriteLine("Unhandled Exception: " + ex);
            MessageBox.Show(ex.Message);
        }

        private void OnKeyPressed(object sender, InputEventArg e)
        {
            if (e.KeyPressEvent.DeviceName.Equals(readerDevide))
            {
                isCardReader = true;
                txtBiensora.ReadOnly = true;

            }
            else
            {
                isCardReader = false;
                txtBiensora.ReadOnly = false;
            }
        }

        private void ReadFromCardReader(KeyPressEventArgs e)
        {
            if (e.KeyChar != 13)
            {
                tempNumber = tempNumber + e.KeyChar;
                readOk = false;
                e.Handled = true;
            }
            else
            {
                cardNumber = tempNumber;
                tempNumber = string.Empty;
                readOk = true;

            }
        }

        private void frmXeRa_FormClosed(object sender, FormClosedEventArgs e)
        {
            _rawinput.KeyPressed -= OnKeyPressed;
        }

        private void frmXeRa_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (isCardReader)
            {
                ReadFromCardReader(e);
                if (readOk)
                {
                    axLiveSau.StartGrapImage(true);
                    countS = 0;
                    axLiveTruoc.StartGrapImage(true);
                    countT = 0;

                    txtSoVe.Text = cardNumber;

                    //Doc bien so
                    Timer_Ra.Enabled = true;
                    //picBiensora.Image = null;
                    btnDocLai.Text = @"Ngừng";
                    lblTrangThai.Text = Constants.StatusReading.Reading;
                    lblTrangThai.ForeColor = Color.Blue;

                    tempFile = DateTime.Now.ToString("yyyyMMddHHmmssffff");

                    //axLiveTruoc.OnGetPicture += axLiveTruoc_OnGetPicture;
                    //img2end = imgT;
                    //picTruoc.Image = imgT;

                    //axLiveSau.OnGetPicture += axLiveSau_OnGetPicture;
                    //img3end = imgS;
                    //picSau.Image = imgS;
                    if (ValidCard())
                    {
                        _xe3 = _xe.ToList().ToList()
                                .OrderByDescending(b => b.NgayVao)
                                .FirstOrDefault(p => p.SoVe.Equals(txtSoVe.Text.Trim()));
                        if (_xe3 != null)
                        {
                            txtBienSoVao.Text = _xe3.BienSoXe;
                            dtpGioVao.Value = ((_xe3.NgayVao.HasValue) ? _xe3.NgayVao.Value : DateTime.Today);
                            dtpNgayvao.Value = ((_xe3.NgayVao.HasValue) ? _xe3.NgayVao.Value : DateTime.Today);
                            foreach (LoaiXe itemx in cbLoaixe.Items)
                            {
                                if (itemx.Id == _xe3.LoaiXe.Id)
                                {
                                    cbLoaixe.SelectedItem = itemx;
                                    break;
                                }

                            }

                            try
                            {
                                //string link = fileUtil.GenerateLink("BIENSOVAO", item.ImgBienXeVao);
                                picBienSoVao.Load(fileUtil.GenerateLink("BIENSOVAO", _xe3.ImgBienXeVao));

                            }
                            catch (Exception)
                            {
                                //MessageBox.Show(ex.Message);
                            }

                            try
                            {
                                imgVaoTruoc.Load(fileUtil.GenerateLink("ANHVAO", _xe3.ImgVaoTruoc));

                            }
                            catch (Exception)
                            {
                                //MessageBox.Show(ex.Message);
                            }

                            try
                            {
                                imgVaoSau.Load(fileUtil.GenerateLink("ANHVAO", _xe3.ImgVaoSau));

                            }
                            catch (Exception)
                            {
                                //MessageBox.Show(ex.Message);
                            }

                        }
                        else
                        {
                            txtBienSoVao.Text = "";
                            dtpGioVao.Value = DateTime.Now;
                            dtpNgayvao.Value = DateTime.Now;
                            picBienSoVao.Image = null;
                            imgVaoTruoc.Image = null;
                            imgVaoSau.Image = null;
                        }
                    }

                    txtBiensora.Focus();
                    txtBiensora.SelectAll();

                }
            }
        }
    }
}
